<?php

/**
 * Description of ACL
 *
 * @author islam
 */
class OSD_Controller_Plugin_ACL extends Zend_Controller_Plugin_Abstract {
 
    public function preDispatch(Zend_Controller_Request_Abstract $request) {
        $objAuth = Zend_Auth::getInstance();
	$clearACL = false;
        
	// initially treat the user as a guest so we can determine if the current
	// resource is accessible by guest users
	$role = 'guest';
 
	// if its not accessible then we need to check for a user login
	// if the user is logged in then we check if the role of the logged
	// in user has the credentials to access the current resource
 
        try {
	    if($objAuth->hasIdentity()) {
	        $arrUser = $objAuth->getIdentity();
                
	         $sess = new Zend_Session_Namespace('OSD_ACL');
	         if($sess->clearACL) {
	             $clearACL = true;
	              unset($sess->clearACL);
	         }
 
                 $objAcl = OSD_ACL_Factory::get($objAuth,$clearACL);
                 
                 //get role name
                 $roleModel = new Administration_Model_Role();
                 $roleinfo = $roleModel->getRoleByID($arrUser->roleId);
                 
	         if(!$objAcl->isAllowed($roleinfo[0]['name'], $request->getModuleName() .'::' .$request->getControllerName().'::'.$request->getActionName())) {
                     
	            $_redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
                    $baseurl = $_redirector->getFrontController()->getBaseUrl();
                    $_redirector->gotoUrl($baseurl); 
                    return;
	         }
 
            } else {
                
	        $objAcl = OSD_ACL_Factory::get($objAuth,$clearACL);
                
	        if(!$objAcl->isAllowed($role, $request->getModuleName() .'::' .$request->getControllerName() .'::' .$request->getActionName())) {
                    
                    $_redirector = Zend_Controller_Action_HelperBroker::getStaticHelper('redirector');
                    $baseurl = $_redirector->getFrontController()->getBaseUrl();
                    $_redirector->gotoUrl($baseurl); 
                    return;
	        }
	    }
        } catch(Zend_Exception $e) {
            $request->setModuleName('default');
            $request->setControllerName('error');
            $request->setActionName('noresource');
            echo $e->getTraceAsString();
        }
    }
}
 